package com.rc.evcharger.service.ugs;

import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.constant.level.UserLevelConstant;
import com.rc.evcharger.mapper.member.MemberInfoMapper;
import com.rc.evcharger.mapper.tenant.TenantOpenServiceMapper;
import com.rc.evcharger.mapper.ugs.*;
import com.rc.evcharger.model.member.MemberInfo;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.model.ugs.*;
import com.rc.evcharger.vo.cost.UserLevelGrowingCount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

/**
 * Create by Yang on 2021/5/25
 */
@Service
public class TenantUgsLevelGrowingServiceImpl implements TenantUgsLevelGrowingService {

    private static Logger logger = LoggerFactory.getLogger(TenantUgsLevelGrowingServiceImpl.class);

    @Autowired
    private TenantUgsLevelGrowingMapper tenantUgsLevelGrowingMapper;

    @Autowired
    private UgsMemberLevelRecordMapper ugsMemberLevelRecordMapper;

    @Autowired
    private TenantUgsMemberLevelMapper tenantUgsMemberLevelMapper;

    @Autowired
    private TenantUgsLevelTypeMapper tenantUgsLevelTypeMapper;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private TenantOpenServiceMapper tenantOpenServiceMapper;

    @Autowired
    private TenantUgsLevelGainMapper tenantUgsLevelGainMapper;

    @Autowired
    private UgsMemberPointRecordService ugsMemberPointRecordService;

    @Override
    public TenantUgsLevelGrowingMapper getMapper() {
        return tenantUgsLevelGrowingMapper;
    }

    /**
     * 会员体系积分&升级
     *
     * @param memberId
     * @param totalPower
     * @param tenantCode
     * @param levelType
     */
    @Override
    public void updateByTotalPower(Long memberId, BigDecimal totalPower, String tenantCode, Long orderInfoId, String accountType) {
        //MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);
        //
        ////互联互通用户不享受折扣
        //if (memberInfo.getMemberType().equals(SocketConstant.STR_CON3)) {
        //    return;
        //}
        //
        ////共享、企业钱包不享受经验值累加
        //if (SocketConstant.STR_CON1.equals(accountType) || SocketConstant.STR_CON2.equals(accountType)) {
        //    return;
        //}
        //
        //if (totalPower.intValue() <= 0) {
        //    return;
        //}
        //
        ////todo 积分新增
        //ugsMemberPointRecordService.insertUgsMemberPointRecord(totalPower.intValue(), memberId, orderInfoId);
        //
        //
        ////TODO 是否开通会员体系、超级会员的功能  使用状态(0:开通,1:停止) 默认 0
        //String levelStatus0 = tenantOpenServiceMapper.selectStatusByTenantAndOpenServiceCode(memberInfo.getTenantCode(), UserLevelConstant.SERVICE_CODE_LEVEL);
        //if (SocketConstant.STR_CON0.equals(levelStatus0)) {
        //    //是否开通对应权益  状态 0启用 1停用 默认0
        //    String gainStatusLevel = tenantUgsLevelGainMapper.selectStatusByTenantCodeAndServiceCode(memberInfo.getTenantCode(), UserLevelConstant.SERVICE_CODE_L);
        //    if (SocketConstant.STR_CON1.equals(gainStatusLevel)) {
        //        return;
        //        //查找对应的会员等级
        //        //TenantUgsMemberLevel tenantUgsMemberLevel = tenantUgsMemberLevelMapper.selectByPrimaryKey(order.getMemberId());
        //        //查询会员优惠价
        //        //levelDiscountStation = tenantUgsLevelDiscountStationMapper.selectValidByEsIdAndType(order.getTenantCode(), tenantUgsMemberLevel.getLevelType(), order.getElecStationId());
        //    }
        //} else {
        //    return;
        //}
        //
        //
        ////查找对应的会员等级
        //TenantUgsMemberLevel tenantUgsMemberLevel = tenantUgsMemberLevelMapper.selectByPrimaryKey(memberId);
        //if (tenantUgsMemberLevel == null) {
        //    logger.error("已开通会员等级，但后台未产生会员等级记录!，对应会员ID：{}", memberId);
        //    return;
        //}
        //
        ////查找成长规则
        //TenantUgsLevelGrowing tenantUgsLevelGrowing = tenantUgsLevelGrowingMapper.selectByTenantCodeAndLevelType(tenantCode, SocketConstant.STR_CON1);
        //if (tenantUgsLevelGrowing == null) {
        //    return;
        //}
        //
        //
        ////定义消费记录
        //UgsMemberLevelRecord ugsMemberLevelRecord = new UgsMemberLevelRecord();
        //ugsMemberLevelRecord.setTenantCode(tenantCode);
        //ugsMemberLevelRecord.setMemberId(memberId);
        //ugsMemberLevelRecord.setGrowingTypeId(tenantUgsLevelGrowing.getLevelGrowingId());
        //ugsMemberLevelRecord.setBeforeValue(tenantUgsMemberLevel.getTotoalExpValue());
        //ugsMemberLevelRecord.setRemark("充电:会员增加成长值");
        //ugsMemberLevelRecord.setCreatedTime(new Date());
        //ugsMemberLevelRecord.setBeforeTime(new Date());
        //ugsMemberLevelRecord.setAfterTime(new Date());
        //ugsMemberLevelRecord.setOrderId(orderInfoId);   //关联订单id
        //ugsMemberLevelRecord.setRecordType(SocketConstant.STR_CON0); //记录类型 0成长 1购买 2赠送 默认0
        //ugsMemberLevelRecord.setBeforeLevelType(tenantUgsMemberLevel.getLevelType()); //变更前等级
        //ugsMemberLevelRecord.setAfterLevelType(tenantUgsMemberLevel.getLevelType()); //变更后等级
        //
        ////当前经验值
        //int totalGrowing = tenantUgsLevelGrowing.getExperienceValue().intValue() * totalPower.intValue();
        //
        ////当天已用经验值
        //UserLevelGrowingCount growingCount = ugsMemberLevelRecordMapper.countChangeValue(tenantUgsLevelGrowing.getLevelGrowingId(), memberId);
        //
        ////限制条件(0:日成长值上限 1:日次数限制)
        //if (SocketConstant.STR_CON0.equals(tenantUgsLevelGrowing.getConditionType())) {
        //    if (growingCount.getGrowingValue() == null || growingCount.getGrowingValue() == 0) {
        //        //未超过成长值限制
        //        if (tenantUgsLevelGrowing.getConditionValue().intValue() >= totalGrowing) {
        //            ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + totalGrowing);
        //            tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
        //        } else {
        //            ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + tenantUgsLevelGrowing.getConditionValue());
        //            tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
        //        }
        //    } else {
        //        //限制值<=当天成长值 达到上限不做处理
        //        if (tenantUgsLevelGrowing.getConditionValue() - growingCount.getGrowingValue() <= 0) {
        //            return;
        //            //限制值>当天成长值 达到上限不做处理
        //        } else if (tenantUgsLevelGrowing.getConditionValue() - growingCount.getGrowingValue() > 0) {
        //            int subValue = tenantUgsLevelGrowing.getConditionValue() - growingCount.getGrowingValue();
        //            if (subValue >= totalGrowing) {
        //                ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + totalGrowing);
        //                tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
        //            } else {
        //                ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + subValue);
        //                tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
        //            }
        //        }
        //    }
        //} else {
        //    //次数未达到限制
        //    if (tenantUgsLevelGrowing.getConditionValue() - growingCount.getGrowingCount() > 0) {
        //        ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + totalGrowing);
        //        tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
        //    }
        //    return;
        //}
        //
        //
        ////更变前后的会员等级
        //TenantUgsLevelType tenantUgsLevelType = tenantUgsLevelTypeMapper.selectByMaxValue(tenantCode);
        //TenantUgsLevelType oldTenantUgsLevelType = tenantUgsLevelTypeMapper.selectByLevelType(tenantCode, tenantUgsMemberLevel.getLevelType());
        //
        ////已是最大值
        //if (tenantUgsLevelType.getLevelType().equals(oldTenantUgsLevelType.getLevelType())) {
        //    ugsMemberLevelRecord.setAfterLevelType(tenantUgsMemberLevel.getLevelType());
        //}
        //
        ////todo 升级
        //TenantUgsLevelType newTenantUgsLevelType = tenantUgsLevelTypeMapper.selectByBetweenValue(tenantCode, ugsMemberLevelRecord.getAfterValue());
        //if (newTenantUgsLevelType == null) {
        //    newTenantUgsLevelType = tenantUgsLevelType;
        //}
        //if (!oldTenantUgsLevelType.getLevelType().equals(newTenantUgsLevelType.getLevelType())) {
        //    tenantUgsMemberLevel.setLevelType(newTenantUgsLevelType.getLevelType());
        //    ugsMemberLevelRecord.setAfterLevelType(newTenantUgsLevelType.getLevelType());
        //
        //    //更新保级时间
        //    Calendar calendar = Calendar.getInstance();
        //    calendar.add(Calendar.DATE, newTenantUgsLevelType.getExpireDay());
        //    tenantUgsMemberLevel.setKeepTime(calendar.getTime());
        //}
        //tenantUgsMemberLevel.setLastUpdatedTime(new Date());
        //
        ////保存更新记录
        //ugsMemberLevelRecordMapper.insertSelective(ugsMemberLevelRecord);
        ////更新会员等级状态
        //tenantUgsMemberLevelMapper.updateByPrimaryKeySelective(tenantUgsMemberLevel);

    }

    @Override
    public void updateByTotalPower(Long memberId, OrderInfo orderInfo) {
        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);

        //互联互通用户不享受折扣
        if (memberInfo.getMemberType().equals(SocketConstant.STR_CON3)) {
            return;
        }

        //共享、企业钱包不享受经验值累加
        if (SocketConstant.STR_CON1.equals(orderInfo.getAccountType()) || SocketConstant.STR_CON2.equals(orderInfo.getAccountType())) {
            return;
        }

        if (orderInfo.getPayAmount().intValue() <= 0) {
            return;
        }

        //todo 积分新增
        ugsMemberPointRecordService.insertUgsMemberPointRecord(orderInfo.getPayAmount().intValue(), memberId, orderInfo.getOrderId());


        //TODO 是否开通会员体系、超级会员的功能  使用状态(0:开通,1:停止) 默认 0
        String levelStatus0 = tenantOpenServiceMapper.selectStatusByTenantAndOpenServiceCode(memberInfo.getTenantCode(), UserLevelConstant.SERVICE_CODE_LEVEL);
        if (SocketConstant.STR_CON0.equals(levelStatus0)) {
            //是否开通对应权益  状态 0启用 1停用 默认0
            String gainStatusLevel = tenantUgsLevelGainMapper.selectStatusByTenantCodeAndServiceCode(memberInfo.getTenantCode(), UserLevelConstant.SERVICE_CODE_L);
            if (SocketConstant.STR_CON1.equals(gainStatusLevel)) {
                return;
                //查找对应的会员等级
                //TenantUgsMemberLevel tenantUgsMemberLevel = tenantUgsMemberLevelMapper.selectByPrimaryKey(order.getMemberId());
                //查询会员优惠价
                //levelDiscountStation = tenantUgsLevelDiscountStationMapper.selectValidByEsIdAndType(order.getTenantCode(), tenantUgsMemberLevel.getLevelType(), order.getElecStationId());
            }
        } else {
            return;
        }


        //查找对应的会员等级
        TenantUgsMemberLevel tenantUgsMemberLevel = tenantUgsMemberLevelMapper.selectByPrimaryKey(memberId);
        if (tenantUgsMemberLevel == null) {
            logger.error("已开通会员等级，但后台未产生会员等级记录!，对应会员ID：{}", memberId);
            return;
        }

        //查找成长规则
        TenantUgsLevelGrowing tenantUgsLevelGrowing = tenantUgsLevelGrowingMapper.selectByTenantCodeAndLevelType(orderInfo.getTenantCode(), SocketConstant.STR_CON1);
        if (tenantUgsLevelGrowing == null) {
            return;
        }


        //定义消费记录
        UgsMemberLevelRecord ugsMemberLevelRecord = new UgsMemberLevelRecord();
        ugsMemberLevelRecord.setTenantCode(orderInfo.getTenantCode());
        ugsMemberLevelRecord.setMemberId(memberId);
        ugsMemberLevelRecord.setGrowingTypeId(tenantUgsLevelGrowing.getLevelGrowingId());
        ugsMemberLevelRecord.setBeforeValue(tenantUgsMemberLevel.getTotoalExpValue());
        ugsMemberLevelRecord.setRemark("充电:会员增加成长值");
        ugsMemberLevelRecord.setCreatedTime(new Date());
        ugsMemberLevelRecord.setBeforeTime(new Date());
        ugsMemberLevelRecord.setAfterTime(new Date());
        ugsMemberLevelRecord.setOrderId(orderInfo.getOrderId());   //关联订单id
        ugsMemberLevelRecord.setRecordType(SocketConstant.STR_CON0); //记录类型 0成长 1购买 2赠送 默认0
        ugsMemberLevelRecord.setBeforeLevelType(tenantUgsMemberLevel.getLevelType()); //变更前等级
        ugsMemberLevelRecord.setAfterLevelType(tenantUgsMemberLevel.getLevelType()); //变更后等级

        //当前经验值
        int totalGrowing = tenantUgsLevelGrowing.getExperienceValue().intValue() * orderInfo.getTotalPower().intValue();

        //当天已用经验值
        UserLevelGrowingCount growingCount = ugsMemberLevelRecordMapper.countChangeValue(tenantUgsLevelGrowing.getLevelGrowingId(), memberId);

        //限制条件(0:日成长值上限 1:日次数限制)
        if (SocketConstant.STR_CON0.equals(tenantUgsLevelGrowing.getConditionType())) {
            if (growingCount.getGrowingValue() == null || growingCount.getGrowingValue() == 0) {
                //未超过成长值限制
                if (tenantUgsLevelGrowing.getConditionValue().intValue() >= totalGrowing) {
                    ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + totalGrowing);
                    tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
                } else {
                    ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + tenantUgsLevelGrowing.getConditionValue());
                    tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
                }
            } else {
                //限制值<=当天成长值 达到上限不做处理
                if (tenantUgsLevelGrowing.getConditionValue() - growingCount.getGrowingValue() <= 0) {
                    return;
                    //限制值>当天成长值 达到上限不做处理
                } else if (tenantUgsLevelGrowing.getConditionValue() - growingCount.getGrowingValue() > 0) {
                    int subValue = tenantUgsLevelGrowing.getConditionValue() - growingCount.getGrowingValue();
                    if (subValue >= totalGrowing) {
                        ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + totalGrowing);
                        tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
                    } else {
                        ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + subValue);
                        tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
                    }
                }
            }
        } else {
            //次数未达到限制
            if (tenantUgsLevelGrowing.getConditionValue() - growingCount.getGrowingCount() > 0) {
                ugsMemberLevelRecord.setAfterValue(tenantUgsMemberLevel.getTotoalExpValue() + totalGrowing);
                tenantUgsMemberLevel.setTotoalExpValue(ugsMemberLevelRecord.getAfterValue());
            }
            return;
        }


        //更变前后的会员等级
        TenantUgsLevelType tenantUgsLevelType = tenantUgsLevelTypeMapper.selectByMaxValue(orderInfo.getTenantCode());
        TenantUgsLevelType oldTenantUgsLevelType = tenantUgsLevelTypeMapper.selectByLevelType(orderInfo.getTenantCode(), tenantUgsMemberLevel.getLevelType());

        //已是最大值
        if (tenantUgsLevelType.getLevelType().equals(oldTenantUgsLevelType.getLevelType())) {
            ugsMemberLevelRecord.setAfterLevelType(tenantUgsMemberLevel.getLevelType());
        }

        //todo 升级
        TenantUgsLevelType newTenantUgsLevelType = tenantUgsLevelTypeMapper.selectByBetweenValue(orderInfo.getTenantCode(), ugsMemberLevelRecord.getAfterValue());
        if (newTenantUgsLevelType == null) {
            newTenantUgsLevelType = tenantUgsLevelType;
        }
        if (!oldTenantUgsLevelType.getLevelType().equals(newTenantUgsLevelType.getLevelType())) {
            tenantUgsMemberLevel.setLevelType(newTenantUgsLevelType.getLevelType());
            ugsMemberLevelRecord.setAfterLevelType(newTenantUgsLevelType.getLevelType());

            //更新保级时间
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, newTenantUgsLevelType.getExpireDay());
            tenantUgsMemberLevel.setKeepTime(calendar.getTime());
        }
        tenantUgsMemberLevel.setLastUpdatedTime(new Date());

        //保存更新记录
        ugsMemberLevelRecordMapper.insertSelective(ugsMemberLevelRecord);
        //更新会员等级状态
        tenantUgsMemberLevelMapper.updateByPrimaryKeySelective(tenantUgsMemberLevel);

    }
}
